package rs.networx.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import rs.networx.dao.NottificationCategory;
import rs.networx.dao.NottificationDao;
import rs.networx.dao.PersonDao;
//import rs.networx.dao.PostCategory;
import rs.networx.dao.PostDao;
import rs.networx.entity.Nottification;
import rs.networx.entity.Person;
import rs.networx.entity.Post;

public class PostVideoOnMembersWallServlet extends HttpServlet {

	private static final long serialVersionUID = -8470333810778704684L;

	@EJB
	private PersonDao personDao;
	
	@EJB
	private NottificationDao nottificationDao;
	
	@EJB
	private PostDao postDao; 
	
	private String username;
	private String password;
	private Integer intLoggedUserID;
	private Person loggedUser;
	
	private String selectedPersonID;
	private Integer intSelectedPersonID;
	private Person selectedPerson;
	
	private String postTitleVideo;
	private String postTextVideo;
	private String videoPostContent;
	
	private String vanilaURL;
	
	private Post videoPost;
	
	private Set<Person> selectedPersonsFriendsSet;
	private List<Person> selectedPersonsFriendsList;
	
	private Set<Person> loggedUsersFriendsSet;
	private List<Person> loggedUsersFriendsList;
	
	private ArrayList<Person> mutualFriends;

	private List<Post> selectedPersonsOwnedPosts;

	private Integer nottificationsCount;
	
	private boolean areFriends;
	
	private String cleanedUpDateOfBirth;
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

		System.out.println("LOADED PostLinkLoggedUserOnMembersWallServlet");

		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding(response.getCharacterEncoding());

		HttpSession session = request.getSession();	
		loggedUser = (Person)session.getAttribute("logovaniUser");
		
		// selectedPersonForMembersBrowsing...
		selectedPersonID = request.getParameter("personID");
		
		postTitleVideo = request.getParameter("postTitleVideo");
		postTextVideo = request.getParameter("postTextVideo");
		videoPostContent = request.getParameter("videoPostContent");
		
		try {	
			System.out.println("selectedPersonID: " + selectedPersonID);

			intSelectedPersonID = Integer.parseInt(selectedPersonID);
			System.out.println("intSelectedPersonID: " + intSelectedPersonID);
			
			username = loggedUser.getEmail();
			password = loggedUser.getPassword();
			intLoggedUserID = loggedUser.getId();
			System.out.println("loggedUser: " + username + "  " + password + "  " + intLoggedUserID);
			
			System.out.println(postTitleVideo + "  " + postTextVideo + "  " + videoPostContent);
		} catch (Exception e) {
			// 
			//e.printStackTrace();
		}
		
		if(intSelectedPersonID != null){
			// sada na osnovu intSelectedPersonID treba da nadjemo datog selectedPerson-a(selectedPersonForMembersBrowsing)...
			selectedPerson = personDao.findById(intSelectedPersonID);
			System.out.println("selectedPersonForMembersBrowsing: " + selectedPerson);
			
			if(loggedUser != null){
				if(selectedPerson != null){
					try {
						// getting short URL from parameter and transforming it to the embeded URL...
						int index = videoPostContent.indexOf('&');
						if(index == -1){
							vanilaURL = videoPostContent.replace("watch?v=", "v/");
							System.out.println("vanilaURL: " + vanilaURL);
						}else if(index != -1){
							vanilaURL = videoPostContent = videoPostContent.substring(0, videoPostContent.indexOf('&'));
							vanilaURL = videoPostContent.replace("watch?v=", "v/");
							System.out.println("vanilaURL: " + vanilaURL);
						}
					} catch (Exception e) {
						// 
						//e.printStackTrace();
					}
					
					// creating new post...
					videoPost = new Post();
					videoPost.setTitle(postTitleVideo);
					videoPost.setText(postTextVideo);
					videoPost.setType(2);
					videoPost.setContent(vanilaURL);
					videoPost.setDate(Calendar.getInstance().getTime());

					videoPost.setPoster(loggedUser);
					videoPost.setOwner(selectedPerson);

					postDao.persist(videoPost);
					
					// treba jos dodati i notifikaciju da je dati loggedd user okacio novi video post na selected persons wall...
					// adding nottification to selected person...
					Nottification nottification = new Nottification();
					nottification.setOwner(selectedPerson);
					nottification.setTargetID(videoPost.getId());
					nottification.setType(2);
					nottification.setViewed(false);
					nottification.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
				   			  			  " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
										  " Added New Video Clip " + 
										  "<a href=\"" + videoPostContent + "\"" + " target=\"_blank\"" + ">" + 
										  "<i style=" + "\"" + "color: blue" + "\"" + ">" + videoPostContent + "</i>" + "</a>" +  
										  " To Your Wall.");
					nottificationDao.persist(nottification);
					
					// treba dodati i notifikaciju za logged usera da je okacio novi link post na selectedPersons wall...
					// adding nottification to logged user...
					Nottification nottification2 = new Nottification();
					nottification2.setOwner(loggedUser);
					nottification2.setTargetID(videoPost.getId());
					nottification2.setType(2);
					nottification2.setViewed(false);
					nottification2.setLink("You Added New Video Clip " + 
							 			   "<a href=\"" + videoPostContent + "\"" + " target=\"_blank\"" + ">" + 
							 			   "<i style=" + "\"" + "color: blue" + "\"" + ">" + videoPostContent + "</i>" + "</a>" + 
										   " To " + 
							  			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
							  			   " target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
							  			   " Wall.");
					nottificationDao.persist(nottification2);
					
					// sada bi trebalo dodati i notifikaciju za svakog prijatelja selected persona da je logged user okacio novi link post...
					// na selected persons wall...
					selectedPersonsFriendsSet = personDao.getFriends(intSelectedPersonID);
					System.out.println("selectedPersonsFriendsSet: " + selectedPersonsFriendsSet.size());
					
					if(selectedPersonsFriendsSet == null || selectedPersonsFriendsSet.size() == 0){
						// znaci da nema prijatelja, pa idemo dalje...
						System.out.println("selectedPersonsFriendsSet: " + selectedPersonsFriendsSet.size());
						
					}else if(selectedPersonsFriendsSet != null && selectedPersonsFriendsSet.size() > 0){
						selectedPersonsFriendsList = new ArrayList<Person>();
						
						Iterator<Person> iter = selectedPersonsFriendsSet.iterator();
					    while(iter.hasNext()){
					    	selectedPersonsFriendsList.add((Person)iter.next());
					    }
					    System.out.println("selectedPersonsFriendsList: " + selectedPersonsFriendsList.size());
					    
					    // sada treba za svakog prijatelja selected persona da napravimo po notifikaciju...
						for(int i = 0; i < selectedPersonsFriendsList.size(); i++){
							// adding nottification to selected persons friends(koji nisu mutual friends)...
							if(selectedPersonsFriendsList.get(i).getId().equals(intLoggedUserID)){
								continue;
							}
							if(personDao.checkIfMutual(intSelectedPersonID, intLoggedUserID, selectedPersonsFriendsList.get(i).getId()) == false){
								
								Nottification nottification3 = new Nottification();
								nottification3.setOwner(selectedPersonsFriendsList.get(i));
								nottification3.setTargetID(videoPost.getId());
								nottification3.setType(2);
								nottification3.setViewed(false);
								nottification3.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
				   			  			  			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
				   			  			  			   " Added New Video Clip " + 
				   			  			  			   "<a href=\"" + videoPostContent + "\"" + " target=\"_blank\"" + ">" + 
				   			  			  			   "<i style=" + "\"" + "color: blue" + "\"" + ">" + videoPostContent + "</i>" + "</a>" + 
				   			  			  			   " To " + 
				   			  			  			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
				   			  			  			   " target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
							 			  			   " Wall.");
								nottificationDao.persist(nottification3);
							}
						}
					}
					
					// trebalo bi isto da napravimo i po notifikaciju za svakog prijatelja od logged usera da je dati logged user...
					// postovao link na selectedPersons wall...
					loggedUsersFriendsSet = personDao.getFriends(intLoggedUserID);
					System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
					
					if(loggedUsersFriendsSet == null || loggedUsersFriendsSet.size() == 0){
						// znaci da nema prijatelja, pa idemo dalje...
						System.out.println("loggedUsersFriendsSet: " + loggedUsersFriendsSet.size());
						
					}else if(loggedUsersFriendsSet != null && loggedUsersFriendsSet.size() > 0){
						loggedUsersFriendsList = new ArrayList<Person>();
						
						Iterator<Person> iter = loggedUsersFriendsSet.iterator();
					    while(iter.hasNext()){
					    	loggedUsersFriendsList.add((Person)iter.next());
					    }
					    System.out.println("loggedUsersFriendsList: " + loggedUsersFriendsList.size());
					    
					    // sada treba za svakog prijatelja da napravimo po notifikaciju...
						for(int i = 0; i < loggedUsersFriendsList.size(); i++){
							// adding nottification to logged users friends(koji nisu mutual friends)...
							if(loggedUsersFriendsList.get(i).getId().equals(intSelectedPersonID)){
								continue;
							}
							if(personDao.checkIfMutual(intLoggedUserID, intSelectedPersonID, loggedUsersFriendsList.get(i).getId()) == false){
								
								Nottification nottification4 = new Nottification();
								nottification4.setOwner(loggedUsersFriendsList.get(i));
								nottification4.setTargetID(videoPost.getId());
								nottification4.setType(2);
								nottification4.setViewed(false);
								nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
				   			  			  			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
				   			  			  			   " Added New Video Clip " + 
				   			  			  			   "<a href=\"" + videoPostContent + "\"" + " target=\"_blank\"" + ">" + 
				   			  			  			   "<i style=" + "\"" + "color: blue" + "\"" + ">" + videoPostContent + "</i>" + "</a>" + 
				   			  			  			   " To " + 
				   			  			  			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
				   			  			  			   " target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
							 			  			   " Wall.");
								nottificationDao.persist(nottification4);
							}
						}
					}
					
					// sada treba i za sve mutual friends da posaljemo po notifikaciju...
					mutualFriends = personDao.getAllMutualFriends(intLoggedUserID, intSelectedPersonID);
					if(mutualFriends != null && mutualFriends.size() > 0){
						// saljemo notifikacije...
						System.out.println("mutualFriends: " + mutualFriends.size());
						
						for(int i = 0; i < mutualFriends.size(); i++){
							// adding notifications to all mutual friends...
							Nottification nottification4 = new Nottification();
							nottification4.setOwner(mutualFriends.get(i));
							nottification4.setTargetID(videoPost.getId());
							nottification4.setType(2);
							nottification4.setViewed(false);
							nottification4.setLink("<a href=\"GoToSelectedPersonProfileServlet2?personID=" + loggedUser.getId() + "\"" + 
			   			  			  			   " target=\"_blank\"" + ">" + loggedUser.getFirstName() + " " + loggedUser.getLastName() + "</a>" + 
			   			  			  			   " Added New Video Clip " + 
			   			  			  			   "<a href=\"" + videoPostContent + "\"" + " target=\"_blank\"" + ">" + 
			   			  			  			   "<i style=" + "\"" + "color: blue" + "\"" + ">" + videoPostContent + "</i>" + "</a>" +  
			   			  			  			   " To " + 
			   			  			  			   "<a href=\"GoToSelectedPersonProfileServlet2?personID=" + selectedPerson.getId() + "\"" + 
			   			  			  			   " target=\"_blank\"" + ">" + selectedPerson.getFirstName() + " " + selectedPerson.getLastName() + "'s" + "</a>" + 
						 			  			   " Wall.");
							nottificationDao.persist(nottification4);
						}
					}else if(mutualFriends == null || mutualFriends.size() == 0){
						// ne saljemo nista...
						System.out.println("mutualFriends: " + mutualFriends.size());
					}
					
					// vidimo da li su logovani user i selected person za members browsing prijatelji, ako jesu tada logovani user moze da komentarise...
					// na zidu selected person za members browsing, a ako nisu onda ne moze...
					areFriends = personDao.areFriends(intLoggedUserID, intSelectedPersonID);
					System.out.println("areFriends: " + areFriends);
					
					// dobavljamo 10 postova za selektovanog korisnika(selectedPersonForMembersBrowsing) (ako ih ima)...
					selectedPersonsOwnedPosts = personDao.getFirstTenOwnedPosts(intSelectedPersonID);
					
					// sada dobavljamo i notifikacije za datog ulogovanog korisnika ako ih ima...
					nottificationsCount = nottificationDao.getNottificationsCountForLoggedUser(loggedUser);
					
					try {
						System.out.println("selectedPersonsOwnedPosts: " + selectedPersonsOwnedPosts.size());
						System.out.println("nottificationsCount: " + nottificationsCount);
					} catch (Exception e) {
						//
						e.printStackTrace();
					}
					
					cleanedUpDateOfBirth = cleanUpDateOfBirth(selectedPerson.getDob());
					System.out.println(cleanedUpDateOfBirth);
					
					// postavljamo podatke na zahtev i na sesiju...
					request.setAttribute("selectedPersonForMembersBrowsing", selectedPerson);
					request.setAttribute("selectedPersonForMembersBrowsingPosts", selectedPersonsOwnedPosts);
					request.setAttribute("areFriends", areFriends);
					request.setAttribute("cleanedUpDateOfBirthForMembersBrowsing", cleanedUpDateOfBirth);
					
					// sada za logovanog korisnika postavljamo na sesiju nonviewed notifikacije (ako ih ima)...
					session.setAttribute("nottificationsCount", nottificationsCount);
					
					// redirektujemo na RegistredUserHomePageForMembers stranicu...
					RequestDispatcher disp = request.getRequestDispatcher("SelectedPersonPostsPage.jsp");
					disp.forward(request, response);
					
				}else if(selectedPerson == null){
					request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
					return;
				}
			}else if(loggedUser == null){
				request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
				return;
			}
		}else if(intSelectedPersonID == null){
			request.getRequestDispatcher("WelcomePage.jsp").forward(request, response);
			return;
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		doGet(request, response);
	}
	
	private String cleanUpDateOfBirth(Date dateOfBirth){
		String result = null;
		
		if(selectedPerson != null){
			System.out.println(dateOfBirth);
			
			String dateOfBirthDB = dateOfBirth.toString();
			
			int i = dateOfBirthDB.indexOf(" ");
			System.out.println("i: " + i);
			
			String temp = dateOfBirthDB.substring(0, i);
			System.out.println("ddd: " + temp);
			
			String[] array = temp.split("-");
			
			System.out.println(array[0]);
			System.out.println(array[1]);
			System.out.println(array[2]);
			System.out.println(array[2] + "/" + array[1] + "/" + array[0]);
			
			result = array[2] + "/" + array[1] + "/" + array[0];
		}
		return result;
	}
	
	
}
